<template>
	<view class="page uni-flex-column">
		<CustomNavBar title="零付" />
		<view class="sticky-city-head">
			<city-head></city-head>
		</view>
		<scroll-view class="scroll-container" scroll-y @scroll="onContainerScroll" @scrolltolower="onScrollToLower">
			<view class="box_1">
				<!-- <city-head></city-head> -->
				<view class="block_2">
					<uni-swiper-dot class="uni-swiper-dot-box" :info="bannerList" :current="currentSwiper" mode="round"
						:dots-styles="dotsStyles" field="content">
						<swiper class="swiper-box" :autoplay="true" :interval="5000" :duration="500"
							:current="currentSwiper" @change="changeSwiper" circular>
							<swiper-item v-for="(item, index) in bannerList" :key="index">
								<view class="swiper-item" @click="goPages(item)">
									<image class="image_2" mode="aspectFill" :src="item.url" />
								</view>
							</swiper-item>
						</swiper>
					</uni-swiper-dot>
				</view>
				<view class="block_3 uni-flex uni-justify-between">
					<!-- 四个功能按钮不变 -->
					<view class="box" @click="openFindCompany">
						<image class="box_bg" referrerpolicy="no-referrer" :src="`${$ImgBaseUrl}greenbg.png`" />
						<view class="box_content">
							<view class="box_content_1">
								<view class="box_text_1">
									<view class="box_text_title color1">优派</view>
									<view class="box_text_sub color1">Priority</view>
								</view>
							</view>
							<text class="box_content_2 bgcolor1">去了解</text>
						</view>
						<image class="box_icon" referrerpolicy="no-referrer" :src="`${$ImgBaseUrl}priority.png`" />
					</view>
					<view class="box" @click="openFindJob">
						<image class="box_bg" referrerpolicy="no-referrer" :src="`${$ImgBaseUrl}yellowbg.png`" />
						<view class="box_content">
							<view class="box_content_1">
								<view class="box_text_1">
									<view class="box_text_title color2">找活</view>
									<view class="box_text_sub color2">Looking</view>
								</view>
							</view>
							<text class="box_content_2 bgcolor2">去了解</text>
						</view>
						<image class="box_icon" style="width: 143rpx;height: 143rpx;" referrerpolicy="no-referrer" :src="`${$ImgBaseUrl}looking.png`" />
					</view>
					<view class="box" @click="openFindPartTimeJob">
						<image class="box_bg" referrerpolicy="no-referrer" :src="`${$ImgBaseUrl}bluebg.png`" />
						<view class="box_content">
							<view class="box_content_1">
								<view class="box_text_1">
									<view class="box_text_title color3">找兼职</view>
									<view class="box_text_sub color3">Part-time</view>
								</view>
							</view>
							<text class="box_content_2 bgcolor3">去了解</text>
						</view>
						<image class="box_icon" style="width: 162rpx;height: 162rpx;" referrerpolicy="no-referrer" :src="`${$ImgBaseUrl}parttime.png`" />
					</view>
					<view class="box" @click="openFindPeople">
						<image class="box_bg" referrerpolicy="no-referrer" :src="`${$ImgBaseUrl}redbg.png`" />
						<view class="box_content">
							<view class="box_content_1">
								<view class="box_text_1">
									<view class="box_text_title color4">找人</view>
									<view class="box_text_sub color4">People</view>
								</view>
							</view>
							<text class="box_content_2 bgcolor4">去了解</text>
						</view>
						<image class="box_icon" style="width: 143rpx;height: 143rpx;" referrerpolicy="no-referrer" :src="`${$ImgBaseUrl}magnifier.png`" />
					</view>
				</view>
			</view>

			<!-- 标签栏：仅当tabsList有数据时显示 -->
			<view class="block_4" v-if="tabsList.length > 0">
				<z-tabs ref="tabs1" :list="tabsList" :current="current" @change="changeTab" scroll-count="0"
					:active-style="{fontWeight: '600',fontSize: '36rpx',color: '#333333'}"
					:inactive-style="{fontWeight: '400',fontSize: '28rpx',color: '#666666'}">
				</z-tabs>
			</view>

			<!-- 空状态：当tabsList为空且初始化完成时显示 -->
			<view v-if="tabsList.length === 0 && initialized" class="empty-state">
				<text class="empty-text">此区域暂无服务类目</text>
			</view>

			<!-- 内容区域：仅当tabsList有数据时显示 -->
			<swiper class="swiper" :current="current" @change="onChange" v-else style="height: calc(100vh - 274rpx);">
				<swiper-item class="swiper-item" v-for="(item, index) in tabsList" :key="index">
					<home-items ref="listItem" :tabIndex="index" :currentIndex="current" :serviceTabs="item.children"
						:disableRefresh="disableRefresh" :key="item.id + current"
						:item-ids-arr="props.itemIdsArr"></home-items>
				</swiper-item>
			</swiper>
		</scroll-view>
		<CouponPopup :showPopup="showCouponPopup" :couponList="couponList" @closePopup="showCouponPopup = false"
			@getCoupon="handleGetCoupon" />
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		toRefs,
		onMounted,
		onUnmounted
	} from "vue";
	import {
		getServiceByArea,
		getBannerList
	} from "@/api/home.js";
	import CustomNavBar from "@/components/custom-navbar/index.vue";
	import homeItems from "@/pages/home/homeItems.vue";
	import cityHead from "@/components/city-head/index.vue";
	import CouponPopup from '@/components/CouponPopup.vue';
	import {
		getEffectiveCouponList
	} from '@/api/coupon.js';
	import {
		getAreaid,
		getCityCode
	} from "@/common/util.js";
	const props = defineProps({
		// 定义itemIdsArr的类型（数组）和默认值（空数组，避免undefined）
		itemIdsArr: {
			type: Array,
			default: () => [] // 默认值必须是函数（避免多个组件共享同一数组引用）
		}
	});
	const showCouponPopup = ref(false)
	const couponList = ref([]); // 存储接口返回的优惠券数据
	const disableRefresh = ref(false);
	const scrollTop = ref(0);
	const emit = defineEmits(['tabChange']);
	const tabsList = ref([]); // 一级类目列表
	const current = ref(0);
	const tabs = ref([]);
	const initialized = ref(false);
	const bannerList = ref([])
	const currentSwiper = ref(0);
	const listItem = ref(null);
	// 添加首次登录状态检查
	const isFirstLogin = ref(false);
	const dotsStyles = reactive({
		backgroundColor: 'rgba(255, 255, 255, 0.7)',
		color: '#fff',
		selectedBackgroundColor: '#2F80ED',
		selectedBorder: 'none',
		border: 'none'
	});

	const state = reactive({
		pattern: {
			color: "#7A7E83",
			backgroundColor: "#fff",
			selectedColor: "#007AFF",
			buttonColor: "#007AFF",
			iconColor: "#fff",
			icon: "star"
		}
	});

	const onContainerScroll = (e) => {
		scrollTop.value = e.detail.scrollTop;
		disableRefresh.value = e.detail.scrollTop > 300;
	};

	const onScrollToLower = () => {
		disableRefresh.value = true;
	};

	const changeTab = (index) => {
		current.value = index;
		// 不在这里调用reload，避免重复请求
		// 改为由onChange方法统一处理
	};

	const onChange = (e) => {
		// 只有当用户手动滑动内容区域时才更新current
		// 如果是标签切换触发的，current已经在changeTab中更新了
		if (e.detail.source === 'touch') {
			current.value = e.detail.current;
		}

		// 触发当前标签页的数据刷新
		if (listItem.value && listItem.value[current.value]) {
			listItem.value[current.value].reload();
		}
	};

	const changeSwiper = (e) => {
		currentSwiper.value = e.detail.current;
	};

	const reloadCurrentList = () => {
		if (listItem.value && listItem.value[current.value]) {
			listItem.value[current.value].reload();
		}
	};

	const openFindPartTimeJob = () => {
		uni.navigateTo({
			url: "/pages/tabBars/findPartTimeJob/index"
		});
	};

	const openFindPeople = () => {
		uni.navigateTo({
			url: "/pages/tabBars/findPeople/index"
		});
	};

	const openFindJob = () => {
		uni.navigateTo({
			url: "/pages/tabBars/findJob/index"
		});
	};

	const openFindCompany = () => {
		uni.navigateTo({
			url: '/pages/viewSonic/viewSonic?from=home'
		});
	};
	const goPages = (item) => {
		console.log('item', item)
		if (item.id === 1) {
			uni.navigateTo({
				url: '/pages/personalCenter/BaichengOperations/BaichengOperationsPage'
			})
		}

	}
	const handleGetCoupon = () => {
		uni.navigateTo({
			url: '/pages/viewSonic/ViewCoupon'
		})
		showCouponPopup.value = false;
	}
	const handleCloseCouponPopup = () => {
		showCouponPopup.value = false;
	};
	const ApigetServiceByArea = async (areaId) => {
		const requestAreaId = areaId || getAreaid();
		tabsList.value = [];
		tabs.value = [];
		initialized.value = false;

		try {
			const res = await getServiceByArea({
				areaId: requestAreaId
			});

			if (res.code !== 200) {
				throw new Error(`接口请求失败：${res.msg || '未知错误'}`);
			}

			const data = res.data || {};
			const firstLevelList = data.serviceList || [];
			const secondLevelList = data.groupList || [];

			// 构建二级类目映射表（按一级类目ID分组）
			const secondLevelMap = {};
			secondLevelList.forEach(group => {
				if (!secondLevelMap[group.parentId]) {
					secondLevelMap[group.parentId] = [];
				}
				secondLevelMap[group.parentId].push(group);
			});

			// 为一级类目添加二级子类目
			tabsList.value = firstLevelList.map(firstLevel => ({
				...firstLevel,
				// 每个一级类目对应的二级类目
				children: secondLevelMap[firstLevel.id] || []
			}));

			tabs.value = secondLevelList;
			initialized.value = true;

			// 初始化第一个标签页的数据
			setTimeout(() => {
				if (listItem.value && listItem.value[0]) {
					listItem.value[0].reload();
				}
			}, 300);

		} catch (err) {
			console.error('获取服务列表失败:', err.message || err);
			uni.showToast({
				title: '此区域暂无服务数据',
				icon: 'none',
				duration: 3000
			});
			tabsList.value = [];
			tabs.value = [];
			initialized.value = true;
		}
	};

	const getBannerListApi = async () => {
		try {
			const res = await getBannerList();
			if (res.code === 200) {
				bannerList.value = res.data || [];
			}
		} catch (error) {
			console.error('获取轮播图失败:', error);
		}
	};
	// 获取优惠券列表
	const fetchCouponList = async () => {
		try {
			const params = {
				pageNum: 1,
				pageSize: 3,
				type: '3',
				usedCity: getCityCode(),
			};
			const res = await getEffectiveCouponList(params);
			if (res.code === 200 && res?.rows) {
				couponList.value = res?.rows.map(item => ({
					amount: item.usedAmount || 0,
					desc: item.title || '优惠券',
					expireDate: item.validEndTime.slice(0, 10) || '2025-01-01',
				}));
			}
		} catch (error) {
			console.error('获取优惠券列表失败:', error);
		}
	};


	onMounted(() => {
		getBannerListApi();
		ApigetServiceByArea();
		fetchCouponList();

		// 关键：读取本地存储的“服务绑定状态”，判断是否显示弹窗
		const hasBindBusiness = uni.getStorageSync('hasBindBusiness');
		if (hasBindBusiness) {
			// 确保优惠券列表已获取（避免弹窗内容为空），延迟100ms显示（可选）
			setTimeout(() => {
				showCouponPopup.value = true; // 显示弹窗
			}, 100);
			// 清除标记：避免下次进入首页重复弹窗
			uni.removeStorageSync('hasBindBusiness');
		}

		uni.$off('areaSelected', handleAreaSelected);
		uni.$on('areaSelected', handleAreaSelected);
	});

	const handleAreaSelected = (data) => {
		if (data?.areaId) {
			ApigetServiceByArea(data.areaId);
		}
	};

	onUnmounted(() => {
		uni.$off('areaSelected', handleAreaSelected);
	});
</script>

<style lang="scss" scoped>
	.page {
		// background: radial-gradient(100% 201% at 16% 46%,
		// 		#e2efff 0%,
		// 		rgba(255, 255, 255, 0) 100%,
		// 		rgba(255, 255, 255, 0) 100%);
		background: radial-gradient( 100% 201% at 16% 6%, #E2EFFF 0%, rgba(255,255,255,0) 100%, rgba(255,255,255,0) 100%);
		min-height: 100vh;
		display: flex;
		flex-direction: column;

		.sticky-city-head {
			position: sticky;
			top: 0;
			z-index: 99;
		}

		.box_1 {
			padding-bottom: 60rpx;
			text-align: center;

			.text_1 {
				font-weight: 500;
				font-size: 36rpx;
				color: #303133;
				line-height: 44rpx;
				margin: 48rpx 0 0;
			}

			.block_2 {
				padding: 0 24rpx;

				.swiper-box {
					border-radius: 8rpx;
					overflow: hidden;
				}

				.swiper-item {
					border-radius: 8rpx;
					overflow: hidden;
				}

				.image_2 {
					width: 100%;
					height: 280rpx;
					border-radius: 8rpx;
				}
			}

			.block_3 {
				padding: 0 24rpx;
				margin-top: 32rpx;
				flex-wrap: wrap;

				.box {
					width: 49%;
					height: 160rpx;
					position: relative;
					margin-bottom: 31rpx;

					.box_bg {
						width: 100%;
						height: 160rpx;
						position: absolute;
						left: 0;
						top: 0;
						z-index: 1;
					}

					.box_content {
						position: absolute;
						z-index: 2;

						.box_text_1 {
							margin: 24rpx 0 0 26rpx;
							text-align: left;

							.box_text_title {
								font-weight: 600;
								font-size: 32rpx;
								line-height: 45rpx;
							}

							.box_text_sub {
								font-size: 25rpx;
								line-height: 15px;
							}
						}

						.box_content_2 {
							border-radius: 18rpx;
							font-size: 20rpx;
							color: #ffffff;
							line-height: 28rpx;
							text-align: center;
							padding: 4rpx 14rpx;
							margin-top: 10rpx;
							float: left;
							margin-left: 26rpx;
						}

						.color1 {
							color: #3fa865;
						}

						.color2 {
							color: #d7970c;
						}

						.color3 {
							color: #2f80ed;
						}

						.color4 {
							color: #ff6a47;
						}

						.bgcolor1 {
							background-color: #6bc98d;
						}

						.bgcolor2 {
							background-color: #feb310;
						}

						.bgcolor3 {
							background-color: #2f80ed;
						}

						.bgcolor4 {
							background-color: #ff6a47;
						}
					}

					.box_icon {
						position: absolute;
						width: 145rpx;
						height: 145rpx;
						right: 11rpx;
						top: -23rpx;
						z-index: 2;
					}
				}
			}
		}

		.block_4 {
			background: #fff;
			border-radius: 30rpx 30rpx 0 0;
			padding: 26rpx 0 0;
			margin-top: -60rpx;
			z-index: 100;
			position: sticky;
			top: 0;
		}

		.swiper {
			height: calc(100vh - 274rpx);
		}

		.fab_btn {
			position: fixed;
			right: 42rpx;
			bottom: 166rpx;
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			background: #ffffff;
			box-shadow: 0rpx 7rpx 17rpx 0rpx #dfe1e4;
		}
	}

	.empty-state {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 30%;
		min-height: 500rpx;
		background: #fff;
		margin-top: -60rpx;

		.empty-text {
			font-size: 30rpx;
			color: #999999;
			text-align: center;
		}
	}

	.scroll-container {
		height: calc(100vh - 280rpx);
		width: 100%;
	}
</style>